3 * Storage medium specific cache for storing items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\WaitConditionLoop
;
27 * Storage medium specific cache for storing items (e.g. redis, memcached, ...)
29 * This should not be used for proxy classes that simply wrap other cache instances
34 abstract class MediumSpecificBagOStuff
extends BagOStuff
{
35 /** @var array[] Lock tracking */
36 protected $locks = [];
37 /** @var int ERR_* class constant */
38 protected $lastError = self
::ERR_NONE
;
40 protected $keyspace = 'local';
41 /** @var int Seconds */
42 protected $syncTimeout;
43 /** @var int Bytes; chunk size of segmented cache values */
44 protected $segmentationSize;
45 /** @var int Bytes; maximum total size of a segmented cache value */
46 protected $segmentedValueMaxSize;
49 private $duplicateKeyLookups = [];
51 private $reportDupes = false;
53 private $dupeTrackScheduled = false;
55 /** @var callable[] */
56 protected $busyCallbacks = [];
58 /** @var string Component to use for key construction of blob segment keys */
59 const SEGMENT_COMPONENT
= 'segment';
62 * @see BagOStuff::__construct()
63 * Additional $params options include:
64 * - logger: Psr\Log\LoggerInterface instance
65 * - keyspace: Default keyspace for $this->makeKey()
66 * - reportDupes: Whether to emit warning log messages for all keys that were
67 * requested more than once (requires an asyncHandler).
68 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
69 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
70 * not exceed the maximum size of values in the storage backend, as configured by
71 * the site administrator.
72 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
73 * This should be configured to a reasonable size give the site traffic and the
74 * amount of I/O between application and cache servers that the network can handle.
75 * @param array $params
77 public function __construct( array $params = [] ) {
78 parent
::__construct( $params );
80 if ( isset( $params['keyspace'] ) ) {
81 $this->keyspace
= $params['keyspace'];
84 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
85 $this->reportDupes
= true;
88 $this->syncTimeout
= $params['syncTimeout'] ??
3;
89 $this->segmentationSize
= $params['segmentationSize'] ??
8388608; // 8MiB
90 $this->segmentedValueMaxSize
= $params['segmentedValueMaxSize'] ??
67108864; // 64MiB
94 * Get an item with the given key
96 * If the key includes a deterministic input hash (e.g. the key can only have
97 * the correct value) or complete staleness checks are handled by the caller
98 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
99 * This lets tiered backends know they can safely upgrade a cached value to
100 * higher tiers using standard TTLs.
103 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
104 * @return mixed Returns false on failure or if the item does not exist
106 public function get( $key, $flags = 0 ) {
107 $this->trackDuplicateKeys( $key );
109 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
113 * Track the number of times that a given key has been used.
116 private function trackDuplicateKeys( $key ) {
117 if ( !$this->reportDupes
) {
121 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
122 // Track that we have seen this key. This N-1 counting style allows
123 // easy filtering with array_filter() later.
124 $this->duplicateKeyLookups
[$key] = 0;
126 $this->duplicateKeyLookups
[$key] +
= 1;
128 if ( $this->dupeTrackScheduled
=== false ) {
129 $this->dupeTrackScheduled
= true;
130 // Schedule a callback that logs keys processed more than once by get().
131 call_user_func( $this->asyncHandler
, function () {
132 $dups = array_filter( $this->duplicateKeyLookups
);
133 foreach ( $dups as $key => $count ) {
134 $this->logger
->warning(
135 'Duplicate get(): "{key}" fetched {count} times',
136 // Count is N-1 of the actual lookup count
137 [ 'key' => $key, 'count' => $count +
1, ]
147 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
148 * @param mixed|null &$casToken Token to use for check-and-set comparisons
149 * @return mixed Returns false on failure or if the item does not exist
151 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
157 * @param mixed $value
158 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
159 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
160 * @return bool Success
162 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
164 is_int( $value ) ||
// avoid breaking incr()/decr()
165 ( $flags & self
::WRITE_ALLOW_SEGMENTS
) != self
::WRITE_ALLOW_SEGMENTS ||
166 is_infinite( $this->segmentationSize
)
168 return $this->doSet( $key, $value, $exptime, $flags );
171 $serialized = $this->serialize( $value );
172 $segmentSize = $this->getSegmentationSize();
173 $maxTotalSize = $this->getSegmentedValueMaxSize();
175 $size = strlen( $serialized );
176 if ( $size <= $segmentSize ) {
177 // Since the work of serializing it was already done, just use it inline
180 SerializedValueContainer
::newUnified( $serialized ),
184 } elseif ( $size > $maxTotalSize ) {
185 $this->setLastError( "Key $key exceeded $maxTotalSize bytes." );
192 $count = intdiv( $size, $segmentSize ) +
( ( $size %
$segmentSize ) ?
1 : 0 );
193 for ( $i = 0; $i < $count; ++
$i ) {
194 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
195 $hash = sha1( $segment );
196 $chunkKey = $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $hash );
197 $chunksByKey[$chunkKey] = $segment;
198 $segmentHashes[] = $hash;
201 $flags &= ~self
::WRITE_ALLOW_SEGMENTS
; // sanity
202 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
204 // Only when all segments are stored should the main key be changed
207 SerializedValueContainer
::newSegmented( $segmentHashes ),
220 * @param mixed $value
221 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
222 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
223 * @return bool Success
225 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
230 * For large values written using WRITE_ALLOW_SEGMENTS, this only deletes the main
231 * segment list key unless WRITE_PRUNE_SEGMENTS is in the flags. While deleting the segment
232 * list key has the effect of functionally deleting the key, it leaves unused blobs in cache.
235 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
236 * @return bool True if the item was deleted or not found, false on failure
238 public function delete( $key, $flags = 0 ) {
239 if ( ( $flags & self
::WRITE_PRUNE_SEGMENTS
) != self
::WRITE_PRUNE_SEGMENTS
) {
240 return $this->doDelete( $key, $flags );
243 $mainValue = $this->doGet( $key, self
::READ_LATEST
);
244 if ( !$this->doDelete( $key, $flags ) ) {
248 if ( !SerializedValueContainer
::isSegmented( $mainValue ) ) {
249 return true; // no segments to delete
252 $orderedKeys = array_map(
253 function ( $segmentHash ) use ( $key ) {
254 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
256 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
259 return $this->deleteMulti( $orderedKeys, $flags );
266 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
267 * @return bool True if the item was deleted or not found, false on failure
269 abstract protected function doDelete( $key, $flags = 0 );
272 * Merge changes into the existing cache value (possibly creating a new one)
274 * The callback function returns the new value given the current value
275 * (which will be false if not present), and takes the arguments:
276 * (this BagOStuff, cache key, current value, TTL).
277 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
278 * Nothing is stored nor deleted if the callback returns false.
281 * @param callable $callback Callback method to be executed
282 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
283 * @param int $attempts The amount of times to attempt a merge in case of failure
284 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
285 * @return bool Success
286 * @throws InvalidArgumentException
288 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
289 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
294 * @param callable $callback Callback method to be executed
295 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
296 * @param int $attempts The amount of times to attempt a merge in case of failure
297 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
298 * @return bool Success
299 * @see BagOStuff::merge()
302 final protected function mergeViaCas( $key, callable
$callback, $exptime, $attempts, $flags ) {
304 $casToken = null; // passed by reference
305 // Get the old value and CAS token from cache
306 $this->clearLastError();
307 $currentValue = $this->resolveSegments(
309 $this->doGet( $key, self
::READ_LATEST
, $casToken )
311 if ( $this->getLastError() ) {
312 $this->logger
->warning(
313 __METHOD__
. ' failed due to I/O error on get() for {key}.',
317 return false; // don't spam retries (retry only on races)
320 // Derive the new value from the old value
321 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
322 $hadNoCurrentValue = ( $currentValue === false );
323 unset( $currentValue ); // free RAM in case the value is large
325 $this->clearLastError();
326 if ( $value === false ) {
327 $success = true; // do nothing
328 } elseif ( $hadNoCurrentValue ) {
329 // Try to create the key, failing if it gets created in the meantime
330 $success = $this->add( $key, $value, $exptime, $flags );
332 // Try to update the key, failing if it gets changed in the meantime
333 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
335 if ( $this->getLastError() ) {
336 $this->logger
->warning(
337 __METHOD__
. ' failed due to I/O error for {key}.',
341 return false; // IO error; don't spam retries
344 } while ( !$success && --$attempts );
350 * Check and set an item
352 * @param mixed $casToken
354 * @param mixed $value
355 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
356 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
357 * @return bool Success
359 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
360 if ( !$this->lock( $key, 0 ) ) {
361 return false; // non-blocking
364 $curCasToken = null; // passed by reference
365 $this->doGet( $key, self
::READ_LATEST
, $curCasToken );
366 if ( $casToken === $curCasToken ) {
367 $success = $this->set( $key, $value, $exptime, $flags );
370 __METHOD__
. ' failed due to race condition for {key}.',
374 $success = false; // mismatched or failed
377 $this->unlock( $key );
383 * Change the expiration on a key if it exists
385 * If an expiry in the past is given then the key will immediately be expired
387 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
388 * main segment list key. While lowering the TTL of the segment list key has the effect of
389 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
390 * Raising the TTL of such keys is not effective, since the expiration of a single segment
391 * key effectively expires the entire value.
394 * @param int $exptime TTL or UNIX timestamp
395 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
396 * @return bool Success Returns false on failure or if the item does not exist
399 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
400 return $this->doChangeTTL( $key, $exptime, $flags );
405 * @param int $exptime
409 protected function doChangeTTL( $key, $exptime, $flags ) {
410 if ( !$this->lock( $key, 0 ) ) {
414 $expiry = $this->getExpirationAsTimestamp( $exptime );
415 $delete = ( $expiry != self
::TTL_INDEFINITE
&& $expiry < $this->getCurrentTime() );
417 // Use doGet() to avoid having to trigger resolveSegments()
418 $blob = $this->doGet( $key, self
::READ_LATEST
);
421 $ok = $this->doDelete( $key, $flags );
423 $ok = $this->doSet( $key, $blob, $exptime, $flags );
429 $this->unlock( $key );
435 * Acquire an advisory lock on a key string
437 * Note that if reentry is enabled, duplicate calls ignore $expiry
440 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
441 * @param int $expiry Lock expiry [optional]; 1 day maximum
442 * @param string $rclass Allow reentry if set and the current lock used this value
443 * @return bool Success
445 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
446 // Avoid deadlocks and allow lock reentry if specified
447 if ( isset( $this->locks
[$key] ) ) {
448 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
449 ++
$this->locks
[$key]['depth'];
457 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
458 $loop = new WaitConditionLoop(
459 function () use ( $key, $expiry, $fname ) {
460 $this->clearLastError();
461 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
462 return WaitConditionLoop
::CONDITION_REACHED
; // locked!
463 } elseif ( $this->getLastError() ) {
464 $this->logger
->warning(
465 $fname . ' failed due to I/O error for {key}.',
469 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
472 return WaitConditionLoop
::CONDITION_CONTINUE
;
477 $code = $loop->invoke();
478 $locked = ( $code === $loop::CONDITION_REACHED
);
480 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
481 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
482 $this->logger
->warning(
483 "$fname failed due to timeout for {key}.",
484 [ 'key' => $key, 'timeout' => $timeout ]
492 * Release an advisory lock on a key string
495 * @return bool Success
497 public function unlock( $key ) {
498 if ( !isset( $this->locks
[$key] ) ) {
502 if ( --$this->locks
[$key]['depth'] <= 0 ) {
503 unset( $this->locks
[$key] );
505 $ok = $this->doDelete( "{$key}:lock" );
507 $this->logger
->warning(
508 __METHOD__
. ' failed to release lock for {key}.',
520 * Delete all objects expiring before a certain date.
521 * @param string|int $timestamp The reference date in MW or TS_UNIX format
522 * @param callable|null $progress Optional, a function which will be called
523 * regularly during long-running operations with the percentage progress
524 * as the first parameter. [optional]
525 * @param int $limit Maximum number of keys to delete [default: INF]
527 * @return bool Success; false if unimplemented
529 public function deleteObjectsExpiringBefore(
531 callable
$progress = null,
538 * Get an associative array containing the item for each of the keys that have items.
539 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
540 * @param int $flags Bitfield; supports READ_LATEST [optional]
541 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
543 public function getMulti( array $keys, $flags = 0 ) {
544 $foundByKey = $this->doGetMulti( $keys, $flags );
547 foreach ( $keys as $key ) {
548 // Resolve one blob at a time (avoids too much I/O at once)
549 if ( array_key_exists( $key, $foundByKey ) ) {
550 // A value should not appear in the key if a segment is missing
551 $value = $this->resolveSegments( $key, $foundByKey[$key] );
552 if ( $value !== false ) {
562 * Get an associative array containing the item for each of the keys that have items.
563 * @param string[] $keys List of keys
564 * @param int $flags Bitfield; supports READ_LATEST [optional]
565 * @return array Map of (key => value) for existing keys
567 protected function doGetMulti( array $keys, $flags = 0 ) {
569 foreach ( $keys as $key ) {
570 $val = $this->doGet( $key, $flags );
571 if ( $val !== false ) {
580 * Batch insertion/replace
582 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
584 * @param mixed[] $data Map of (key => value)
585 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
586 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
587 * @return bool Success
590 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
591 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
592 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
594 return $this->doSetMulti( $data, $exptime, $flags );
598 * @param mixed[] $data Map of (key => value)
599 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
600 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
601 * @return bool Success
603 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
605 foreach ( $data as $key => $value ) {
606 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
614 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
616 * @param string[] $keys List of keys
617 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
618 * @return bool Success
621 public function deleteMulti( array $keys, $flags = 0 ) {
622 if ( ( $flags & self
::WRITE_ALLOW_SEGMENTS
) === self
::WRITE_ALLOW_SEGMENTS
) {
623 throw new InvalidArgumentException( __METHOD__
. ' got WRITE_ALLOW_SEGMENTS' );
625 return $this->doDeleteMulti( $keys, $flags );
629 * @param string[] $keys List of keys
630 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
631 * @return bool Success
633 protected function doDeleteMulti( array $keys, $flags = 0 ) {
635 foreach ( $keys as $key ) {
636 $res = $this->doDelete( $key, $flags ) && $res;
642 * Change the expiration of multiple keys that exist
644 * @param string[] $keys List of keys
645 * @param int $exptime TTL or UNIX timestamp
646 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
647 * @return bool Success
648 * @see BagOStuff::changeTTL()
652 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
654 foreach ( $keys as $key ) {
655 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
662 * Decrease stored value of $key by $value while preserving its TTL
664 * @param int $value Value to subtract from $key (default: 1) [optional]
665 * @return int|bool New value or false on failure
667 public function decr( $key, $value = 1 ) {
668 return $this->incr( $key, -$value );
672 * Increase stored value of $key by $value while preserving its TTL
674 * This will create the key with value $init and TTL $ttl instead if not present
680 * @return int|bool New value or false on failure
683 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
684 $this->clearLastError();
685 $newValue = $this->incr( $key, $value );
686 if ( $newValue === false && !$this->getLastError() ) {
687 // No key set; initialize
688 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
689 if ( $newValue === false && !$this->getLastError() ) {
690 // Raced out initializing; increment
691 $newValue = $this->incr( $key, $value );
699 * Get and reassemble the chunks of blob at the given key
702 * @param mixed $mainValue
703 * @return string|null|bool The combined string, false if missing, null on error
705 final protected function resolveSegments( $key, $mainValue ) {
706 if ( SerializedValueContainer
::isUnified( $mainValue ) ) {
707 return $this->unserialize( $mainValue->{SerializedValueContainer
::UNIFIED_DATA
} );
710 if ( SerializedValueContainer
::isSegmented( $mainValue ) ) {
711 $orderedKeys = array_map(
712 function ( $segmentHash ) use ( $key ) {
713 return $this->makeGlobalKey( self
::SEGMENT_COMPONENT
, $key, $segmentHash );
715 $mainValue->{SerializedValueContainer
::SEGMENTED_HASHES
}
718 $segmentsByKey = $this->doGetMulti( $orderedKeys );
721 foreach ( $orderedKeys as $segmentKey ) {
722 if ( isset( $segmentsByKey[$segmentKey] ) ) {
723 $parts[] = $segmentsByKey[$segmentKey];
725 return false; // missing segment
729 return $this->unserialize( implode( '', $parts ) );
736 * Get the "last error" registered; clearLastError() should be called manually
737 * @return int ERR_* constant for the "last error" registry
740 public function getLastError() {
741 return $this->lastError
;
745 * Clear the "last error" registry
748 public function clearLastError() {
749 $this->lastError
= self
::ERR_NONE
;
753 * Set the "last error" registry
754 * @param int $err ERR_* constant
757 protected function setLastError( $err ) {
758 $this->lastError
= $err;
762 * Let a callback be run to avoid wasting time on special blocking calls
764 * The callbacks may or may not be called ever, in any particular order.
765 * They are likely to be invoked when something WRITE_SYNC is used used.
766 * They should follow a caching pattern as shown below, so that any code
767 * using the work will get it's result no matter what happens.
770 * $workCallback = function () use ( &$result ) {
778 * @param callable $workCallback
781 final public function addBusyCallback( callable
$workCallback ) {
782 $this->busyCallbacks
[] = $workCallback;
786 * @param int|float $exptime
787 * @return bool Whether the expiry is non-infinite, and, negative or not a UNIX timestamp
790 final protected function isRelativeExpiration( $exptime ) {
791 return ( $exptime !== self
::TTL_INDEFINITE
&& $exptime < ( 10 * self
::TTL_YEAR
) );
795 * Convert an optionally relative timestamp to an absolute time
797 * The input value will be cast to an integer and interpreted as follows:
798 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
799 * - negative: relative TTL; return UNIX timestamp offset by this value
800 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
801 * - positive (>= 10 years): absolute UNIX timestamp; return this value
803 * @param int $exptime
804 * @return int Expiration timestamp or TTL_INDEFINITE for indefinite
807 final protected function getExpirationAsTimestamp( $exptime ) {
808 if ( $exptime == self
::TTL_INDEFINITE
) {
812 return $this->isRelativeExpiration( $exptime )
813 ?
intval( $this->getCurrentTime() +
$exptime )
818 * Convert an optionally absolute expiry time to a relative time. If an
819 * absolute time is specified which is in the past, use a short expiry time.
821 * The input value will be cast to an integer and interpreted as follows:
822 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
823 * - negative: relative TTL; return a short expiry time (1 second)
824 * - positive (< 10 years): relative TTL; return this value
825 * - positive (>= 10 years): absolute UNIX timestamp; return offset to current time
827 * @param int $exptime
828 * @return int Relative TTL or TTL_INDEFINITE for indefinite
831 final protected function getExpirationAsTTL( $exptime ) {
832 if ( $exptime == self
::TTL_INDEFINITE
) {
836 return $this->isRelativeExpiration( $exptime )
838 : (int)max( $exptime - $this->getCurrentTime(), 1 );
842 * Check if a value is an integer
844 * @param mixed $value
847 final protected function isInteger( $value ) {
848 if ( is_int( $value ) ) {
850 } elseif ( !is_string( $value ) ) {
854 $integer = (int)$value;
856 return ( $value === (string)$integer );
860 * Construct a cache key.
862 * @param string $keyspace
864 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
867 public function makeKeyInternal( $keyspace, $args ) {
869 foreach ( $args as $arg ) {
870 $key .= ':' . str_replace( ':', '%3A', $arg );
872 return strtr( $key, ' ', '_' );
876 * Make a global cache key.
878 * @param string $class Key class
879 * @param string ...$components Key components (starting with a key collection name)
880 * @return string Colon-delimited list of $keyspace followed by escaped components
883 public function makeGlobalKey( $class, ...$components ) {
884 return $this->makeKeyInternal( 'global', func_get_args() );
888 * Make a cache key, scoped to this instance's keyspace.
890 * @param string $class Key class
891 * @param string ...$components Key components (starting with a key collection name)
892 * @return string Colon-delimited list of $keyspace followed by escaped components
895 public function makeKey( $class, ...$components ) {
896 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
900 * @param int $flag ATTR_* class constant
901 * @return int QOS_* class constant
904 public function getQoS( $flag ) {
905 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
909 * @return int|float The chunk size, in bytes, of segmented objects (INF for no limit)
912 public function getSegmentationSize() {
913 return $this->segmentationSize
;
917 * @return int|float Maximum total segmented object size in bytes (INF for no limit)
920 public function getSegmentedValueMaxSize() {
921 return $this->segmentedValueMaxSize
;
925 * @param mixed $value
926 * @return string|int String/integer representation
927 * @note Special handling is usually needed for integers so incr()/decr() work
929 protected function serialize( $value ) {
930 return is_int( $value ) ?
$value : serialize( $value );
934 * @param string|int $value
935 * @return mixed Original value or false on error
936 * @note Special handling is usually needed for integers so incr()/decr() work
938 protected function unserialize( $value ) {
939 return $this->isInteger( $value ) ?
(int)$value : unserialize( $value );
943 * @param string $text
945 protected function debug( $text ) {
946 if ( $this->debugMode
) {
947 $this->logger
->debug( "{class} debug: $text", [ 'class' => static::class ] );